const plist = require('plist')
const fs = require('fs');
const Jimp = require('jimp');

var plistList = ["frontGame", "game", "guide", "signIn"];
var total = 0;
var countTotal = 0;
//开始时间
var startTime = new Date().getTime(); 
console.log("图片裁剪开始，请耐心等待");
for (let plistListIndex = 0; plistListIndex < plistList.length; plistListIndex++) {
  //读取文件内容 , 用 plist 转内容为 Js 对象
  var fileContent = fs.readFileSync(__dirname + '/plist/' + plistList[plistListIndex] + '.plist', 'utf8');
  //内容转换
  var content = plist.parse(fileContent);
  var imgNameArr = new Array();
  var textureRectArr = new Array();
  var maxCount = 0;
  for (let imgName in content['frames']) {
    imgNameArr.push(imgName);
    maxCount++;
    total++;
  }
  //string转obj
  for (let i = 0; i < imgNameArr.length; i++) {
    let textureRect = content['frames'][imgNameArr[i]].textureRect;
    let textureRotated = content['frames'][imgNameArr[i]].textureRotated;
    let temp = textureRect.slice(2, textureRect.length - 2);
    let temp2 = temp.split("},{");
    let pos = temp2[0].split(",");
    let size = temp2[1].split(",");
    let rect = {};
    if (textureRotated) {
      rect = {
        'x': Number(pos[0]),
        'y': Number(pos[1]),
        'h': Number(size[0]),
        'w': Number(size[1]),
        'r': textureRotated,
      }
    } else {
      rect = {
        'x': Number(pos[0]),
        'y': Number(pos[1]),
        'h': Number(size[1]),
        'w': Number(size[0]),
        'r': textureRotated,
      }
    }
    textureRectArr.push(rect);
  }
  //图片裁剪 crop( x, y, w, h,name,isRotate, fun)
  async function crop(x, y, w, h, name, isRotate, fun) {
    // 读取图片
    var image = await Jimp.read(__dirname + '/plist/' + plistList[plistListIndex] + '.png');
    var newImgge = image.crop(x, y, w, h);
    //是否旋转图片
    if (isRotate) {
      newImgge.rotate(90);
    }
    // 保存 
    await newImgge.writeAsync(name).then(fun());
  }
  //更具plist文件实现图片裁剪
  for (let i = 0; i < maxCount; i++) {
    let name = __dirname + "/imgs/" + plistList[plistListIndex] + '/' + imgNameArr[i];
    crop(textureRectArr[i].x, textureRectArr[i].y, textureRectArr[i].w, textureRectArr[i].h, name, textureRectArr[i].r, () => {
        countTotal++;
        process.stdout.write(`${countTotal} / ${total} \r`);
        if(countTotal>=total){
          let time = (new Date().getTime()-startTime).toFixed(0);
          console.log("裁剪完成,文件路径" + __dirname + "/imgs文件夹下,本次耗时"+time+"毫秒");
        }
       
    });
  }
}

/** 创建目录 */
function msdir(url, fun) {
  fs.mkdir(url, function (err) {
    if (err) {
      fun(false);
    } else {
      fun(true);
    }
  });
}
